<template>
    <div class="auth content flex-col">
        <div class="auth-header flex-row">
            <div class="flex-row">
                <span class="iconfont cgsIcon-left auth-return" @click="$router.back()"/>
                    你是此应用的管理员，可以配置应用，角色和成员
                <div>
                    <span class="detail" @click="dialogAppIdVisible = true">获取应用ID</span>
                </div>
            </div>
            <a-radio-group v-model="roleSwitch" button-style="solid">
              <a-radio-button value="admin">管理员</a-radio-button>
              <a-radio-button value="role">角色</a-radio-button>
            </a-radio-group>
        </div>
        <div class="auth-content flex-col no-select">
            <div v-if="roleSwitch === 'admin'" class="auth-card">
                <div class="auth-card-header flex-row"
                     @click.stop="handleRoleClick(admin)"
                >
                    <div class="auth-card-left">
                        应用管理员
                        <div class="auth-card-des">{{admin.desc}}</div>
                    </div>
                    <div class="auth-card-right flex-row">
                        <div class="auth-card-count">{{admin.userSize}}人</div>
                        <span class="iconfont cgsIcon-rounddown auth-card-icon" style="opacity: 0.5"/>
                    </div>
                </div>
                <div v-show="admin.visible" class="auth-card-extend ">
                    <div class="auth-extend-content flex-row">
                        <div class="auth-user flex-row"
                             v-for="user in admin.users"
                             :key="user.userId"
                             @click.stop="handleClickUser(user, admin)"
                        >
                            <el-checkbox v-show="!user.isOwner" v-model="user.check" @change="handleClickUser(user, admin)" />
                            <div class="auth-user-img">{{user.nickName}}</div>
                            <div class="auth-user-name">{{user.nickName}}</div>
                            <div v-show="user.isOwner" class="auth-user-owner">拥有者</div>
                        </div>
                    </div>
                    <div class="auth-extend-footer flex-row">
                        <div class="auth-extend-add" @click.stop="handleAddAppUser(admin)">
                            添加人员
                        </div>
                        <div v-show="admin.showDeleteUser.visible"
                             @click.stop="handleDeleteUsers(admin)"
                             class="auth-extend-delete">
                            人员移除
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="roleSwitch === 'role'">
                <div class="auth-card"
                     v-for="role in appRoles"
                     :key="role.id"
                >
                    <div class="auth-card-header flex-row"
                         @click.stop="handleRoleClick(role)"
                    >
                        <div class="auth-card-left">
                            {{role.roleName}}
                            <div class="auth-card-des">{{role.desc}}</div>
                        </div>
                        <div class="auth-card-right flex-row">
                            <span class="iconfont cgsIcon-shanchu auth-card-icon" style="opacity: 0.5" @click.stop="handleDeleteRole(role)"/>
                            <span class="iconfont cgsIcon-xiugai auth-card-icon" style="opacity: 0.5" @click.stop="handleUpdateRole(role)"/>
                            <div class="auth-card-count">{{role.userSize}}人</div>
                            <span class="iconfont cgsIcon-rounddown auth-card-icon" style="opacity: 0.5"/>
                        </div>
                    </div>
                    <div v-show="role.visible" class="auth-card-extend ">
                        <div class="auth-extend-content flex-row">
                            <div class="auth-user flex-row"
                                 v-for="user in role.users"
                                 :key="user.userId"
                                 @click.stop="handleClickUser(user, role)"
                            >
                                <el-checkbox v-model="user.check" @change="handleClickUser(user, role)"></el-checkbox>
                                <div class="auth-user-img">{{user.nickName}}</div>
                                <div class="auth-user-name">{{user.nickName}}</div>
                            </div>
                        </div>
                        <div class="auth-extend-footer flex-row">
                            <div class="auth-extend-add" @click.stop="handleAddAppUser(role)">
                                添加人员
                            </div>
                            <div v-show="role.showDeleteUser.visible"
                                 class="auth-extend-delete"
                                 @click.stop="handleDeleteUsers(role)"
                            >
                                人员移除
                            </div>
                        </div>
                    </div>
                </div>

                <div class="auth-card">
                    <div class="auth-card-header flex-row"
                         @click.stop="handleAddRole"
                    >
                        <div class="auth-card-left">
                            + 添加角色
                            <div class="auth-card-des">添加角色设置应用权限，控制用户可见的应用</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <el-dialog title="一 添加成员 一"
                   :visible.sync="dialogAddUserVisible"
                   :close-on-click-modal="false"
                   width="400px"
                   center>
            <div style="width: 100%">
                <el-input placeholder="请输入成员名称"
                          suffix-icon="el-icon-search"
                          v-model="searchInput"></el-input>
            </div>
            <div class="auth-add-user">
                <div class="auth-add-user-item flex-row"
                     v-for="user in addUsers"
                     :key="user.userId"
                     @click="user.check = !user.check"
                >
                    <a-checkbox v-model="user.check">
                    </a-checkbox>
                    <div class="auth-add-user-name">{{user.userAlia}}</div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <div class="auth-extend-footer flex-row">
                    <div class="auth-extend-add" @click="handleAddUser">
                        确定
                    </div>
                    <div class="auth-extend-delete" @click="dialogAddUserVisible = false">
                        取消
                    </div>
                </div>
            </div>
        </el-dialog>
        <el-dialog :title="formData.title"
            :width="visualType === 'App'? '95%':'75%'"
            :visible.sync="dialogAddRoleVisible"
            :close-on-click-modal="false"
            :modal="false"
        >
            <el-form :model="formData" :rules="rules" ref="formData">
                <el-form-item label="角色名称：" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="formData.roleName"></el-input>
                </el-form-item>
                <el-form-item label="描 述：" :label-width="formLabelWidth">
                    <el-input v-model="formData.roleDesc"></el-input>
                </el-form-item>
                <div style="width: 100%;height: 400px;overflow-y: auto;">
                    <el-form-item label="应用权限：" :label-width="formLabelWidth">
                        <template>
                            <div><span style="font-size: 16px; color: #409EFF;">应用门户：</span>
                                <el-checkbox :indeterminate="formData.indeterminate.portal"
                                             @change="handleCheckAllAppChange($event, 'portal')"
                                             v-model="formData.checkAll.portal">全选</el-checkbox>
                                <div style="margin: 15px 0;"></div>
                            </div>
                            <el-checkbox-group v-model="formData.roleAuthorities.portal"
                                               @change="handleCheckedAppAuthorityChange($event, 'portal')">
                                <el-checkbox v-for="authority in formData.appAuthorities.portal"
                                             :label="authority.name"
                                             :key="authority.name">
                                    {{authority.alia}}</el-checkbox>
                            </el-checkbox-group>
                        </template>
                        <template>
                            <div><span style="font-size: 16px; color: #409EFF;">应用搭建：</span>
                                <el-checkbox :indeterminate="formData.indeterminate.builder"
                                             @change="handleCheckAllAppChange($event, 'builder')"
                                             v-model="formData.checkAll.builder">全选</el-checkbox>
                                <div style="margin: 15px 0;"></div>
                            </div>
                            <el-checkbox-group v-model="formData.roleAuthorities.builder"
                                               @change="handleCheckedAppAuthorityChange($event, 'builder')">
                                <el-checkbox v-for="authority in formData.appAuthorities.builder"
                                             :label="authority.name"
                                             :key="authority.name">
                                    {{authority.alia}}</el-checkbox>
                            </el-checkbox-group>
                        </template>
                        <template>
                            <div><span style="font-size: 16px; color: #409EFF;">场景建模：</span>
                                <el-checkbox :indeterminate="formData.indeterminate.editor"
                                             @change="handleCheckAllAppChange($event, 'editor')"
                                             v-model="formData.checkAll.editor">全选</el-checkbox>
                                <div style="margin: 15px 0;"></div>
                            </div>
                            <el-checkbox-group v-model="formData.roleAuthorities.editor"
                                               @change="handleCheckedAppAuthorityChange($event, 'editor')">
                                <el-checkbox v-for="authority in formData.appAuthorities.editor"
                                             :label="authority.name"
                                             :key="authority.name">
                                    {{authority.alia}}</el-checkbox>
                            </el-checkbox-group>
                        </template>
                        <template v-if="visualType !== 'App'">
                            <div><span style="font-size: 16px; color: #409EFF;">表单设计：</span>
                                <el-checkbox :indeterminate="formData.indeterminate.form"
                                             @change="handleCheckAllAppChange($event, 'form')"
                                             v-model="formData.checkAll.form">全选</el-checkbox>
                                <div style="margin: 15px 0;"></div>
                            </div>
                            <el-checkbox-group v-model="formData.roleAuthorities.form"
                                               @change="handleCheckedAppAuthorityChange($event, 'form')">
                                <el-checkbox v-for="authority in formData.appAuthorities.form"
                                             :label="authority.name"
                                             :key="authority.name">
                                    {{authority.alia}}</el-checkbox>
                            </el-checkbox-group>
                        </template>
                        <template v-else>
                            <div><span style="font-size: 16px; color: #409EFF;">表单设计：</span>
                            </div>
                            <el-radio v-model="formAuthType" :label="0">所有表单权限</el-radio>
                            <el-radio v-model="formAuthType" :label="1">可选择的表单权限</el-radio>
                            <el-select v-show="formAuthType === 0" v-model="formData.roleAuthorities.form[0]" @change="selectChange" style="width: 100%" placeholder="请选择" size="small">
                                <el-option
                                    v-for="item in formData.appAuthorities.form.filter(f => f.group === 'DistributeAll')"
                                    :key="item.name"
                                    :label="item.alia"
                                    :value="item.name">
                                </el-option>
                            </el-select>
                            <div style="marginLeft: 10px" v-show="formAuthType === 1">
                                <el-checkbox v-model="formAdd">添加表单权限</el-checkbox>
                            </div>
                            <el-table v-show="formAuthType === 1"
                                :data="tableData"
                                style="width: 100%"
                            >
                                <el-table-column
                                    fixed
                                    prop="worksheet"
                                    label="工作表"
                                    width="150">
                                </el-table-column>
                                <el-table-column v-for="item in formAuthorities"
                                    :key="item.name"
                                    :prop="item.name">
                                    <div slot="header">
                                        <el-checkbox @change="value =>handleFormCheckChange(value, item.name)"></el-checkbox>
                                        {{item.alia}}
                                    </div>
                                    <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row[item.name]" @change="value =>handleFormRowCheckChange(value, item.name, scope.row)"></el-checkbox>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                        <template>
                            <div><span style="font-size: 16px; color: #409EFF;">在线开发：</span>
                                <el-checkbox :indeterminate="formData.indeterminate.studio"
                                             @change="handleCheckAllAppChange($event, 'studio')"
                                             v-model="formData.checkAll.studio">全选</el-checkbox>
                                <div style="margin: 15px 0;"></div>
                            </div>
                            <el-checkbox-group v-model="formData.roleAuthorities.studio"
                                               @change="handleCheckedAppAuthorityChange($event, 'studio')">
                                <el-checkbox v-for="authority in formData.appAuthorities.studio"
                                             :label="authority.name"
                                             :key="authority.name">
                                    {{authority.alia}}</el-checkbox>
                            </el-checkbox-group>
                        </template>
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <div class="auth-extend-footer flex-row">
                    <div class="auth-extend-add" @click="handleFormSubmit('formData')">
                        确定
                    </div>
                    <div class="auth-extend-delete" @click="dialogAddRoleVisible = false">
                        取消
                    </div>
                </div>
            </div>
        </el-dialog>
        <el-dialog width="400px"
                   title="一 应用ID 一"
                   center
                   key="getAppID"
                   :visible.sync="dialogAppIdVisible"
        >
            <div>
                应用id
            </div>
            <div>
                {{appId}}
                <span style="color: #4b83e5; margin-left: 20px; cursor: pointer"
                      v-clipboard:copy="appId"
                      v-clipboard:success="handleCopyOk"
                      v-clipboard:error="handleCopyErr"
                >复制</span>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        addRole,
        deleteRole,
        editRole,
        getAppAuthorityList,
        getRoleByID,
        getRoleList,
        getUserList,
        updateUser
    } from '@/api/authority'
    import {getAllWorksheet} from "@/api/app"
    export default {
        name: "authority",
        props: ['appId', 'visualType'],
        data() {
            return {
                appRoles: [],
                formLabelWidth: "120px",
                admin: {
                    showDeleteUser: {}
                },
                currentRole: {},
                roleSwitch: 'admin',
                personNum: 0,
                arrow: true,
                dialogAddUserVisible: false,
                dialogAddRoleVisible: false,
                dialogAppIdVisible: false,

                formAuthType: 0,
                formAdd: false,
                formAuths:{},
                formAuthsCheckAll:{},
                formAuthorities:[],
                tableData: [],

                searchInput: '',
                userData: [],
                submitState: {
                    state: "add",
                    node: {}
                },
                formData: {
                    title: '一 添加角色 一',
                    roleName: "",
                    roleDesc: "自定义权限",
                    appAuthorities: {
                        editor: [],
                        portal: [],
                        form: [],
                        studio: [],
                        builder: [],
                    },
                    indeterminate: {
                        editor: true,
                        portal: true,
                        form: true,
                        studio: true,
                        builder: true,
                    },
                    checkAll: {
                        editor: false,
                        portal: false,
                        form: false,
                        studio: false,
                        builder: false,
                    },
                    roleAuthorities: {
                        editor: [],
                        portal: [],
                        form: [],
                        studio: [],
                        builder: []
                    }
                },
                rules:{
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                }
            }
        },
        computed: {
            addUsers() {
                return this.userData.filter(u => u.userAlia.includes(this.searchInput))
            },
            visualType(){
                return this.$route.params.visualType
            }
        },
        created() {
            getRoleList({
                type: "APP_ROLE",
                visualId: this.appId,
                visualType: this.visualType
            }).then((res) => {
                if (res.data && res.data.code === 200) {
                    this.appRoles = [];

                    for (let i = 0; i < res.data.data.length; i++) {
                        let appRole = res.data.data[i];
                        let users = [];
                        if(appRole.users){
                            for (let j = 0; j < appRole.users.length; j++) {
                                users.push(appRole.users[j]);

                                users[j]["check"] = false;
                            }
                        }
                        let role = {
                            id: appRole.id,
                            roleName: appRole.roleName,
                            userSize: appRole.userSize,
                            desc: appRole.desc,
                            users: users,
                            userIds: appRole.userIds,
                            manage: false,
                            visible: false,
                            showDeleteUser: {
                                visible: false,
                                userSize: 0
                            }
                        }
                        if(appRole.roleAlias === "AppAdministrator" && appRole.type === "APP_ROLE") {
                            this.admin = role;
                        }else {
                            this.appRoles.push(role);
                            // console.log(role)
                        }
                    }
                }
            });


            //获得应用权限列表
            getAppAuthorityList().then((res) => {
                if(res.data && res.data.success){
                    for (let i = 0; i < res.data.data.length; i++) {
                        let authority = res.data.data[i];
                        if (authority.type === 'EDITOR'){
                            this.formData.appAuthorities.editor.push(authority);
                        }
                        else if (authority.type === 'PORTAL'){
                            this.formData.appAuthorities.portal.push(authority);
                        }
                        else if (authority.type === 'FORM'){
                            this.formData.appAuthorities.form.push(authority);
                        }
                        else if (authority.type === 'STUDIO'){
                            this.formData.appAuthorities.studio.push(authority);
                        }else if (authority.type === 'BUILDER'){
                            this.formData.appAuthorities.builder.push(authority);
                        }
                    }
                }
            })
        },
        methods: {
            selectChange(value) {
                this.formData.roleAuthorities.form[0] = value
            },
            handleRoleClick(role) {
                this.arrow = !this.arrow
                role.visible = !role.visible;
            },
            handleCopyOk(){
                this.$message.success('复制成功');
            },
            handleCopyErr(){
                this.$message.error('复制失败');
            },
            handleFormSubmit(formName) {
                this.dialogAddRoleVisible = false;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let authorities = [];
                        for (const roleAuthoritiesKey in this.formData.roleAuthorities) {
                            for (let i = 0; i < this.formData.roleAuthorities[roleAuthoritiesKey].length; i++) {
                                authorities.push(this.formData.roleAuthorities[roleAuthoritiesKey][i])
                            }
                        }
                        if(this.submitState.state === 'add'){
                            let obj = {
                                "roleName": this.formData.roleName,
                                "desc":this.formData.roleDesc,
                                "appAuths": authorities,
                                "type": "APP_ROLE",
                                "visualId": this.appId,
                                "formAuthType": this.formAuthType
                            }
                            
                            if(this.formAuthType === 1){
                                let formAuths = {}
                                this.tableData.forEach(t => {
                                    formAuths[t.worksheetId] = []
                                    for (const key in t) {
                                        const element = t[key];
                                        if(element === true){
                                            formAuths[t.worksheetId].push(key)
                                        }
                                    }
                                })
                                obj.formAuths = formAuths

                                if(this.formAdd && !obj.appAuths.includes('FORM_ADD')){
                                    obj.appAuths.push('FORM_ADD')
                                }
                            }
                            addRole(obj).then((res) => {
                                if (res.data && res.data.code === 200 && res.data.success) {
                                    this.$message.success("添加成功！")
                                    let role = {
                                        id: res.data.data.roleId,
                                        roleName: this.formData.roleName,
                                        userSize: 0,
                                        desc: this.formData.roleDesc,
                                        users: [],
                                        userIds: [],
                                        manage: false,
                                        visible: false,
                                        showDeleteUser: {
                                            visible: false,
                                            userSize: 0
                                        }
                                    }
                                    this.appRoles.push(role);
                                } else {
                                    this.$message.error("添加失败！")
                                }
                            })
                        }
                        else if(this.submitState.state === 'update'){
                            let data = {
                                "id": this.submitState.node.id,
                                "roleName": this.formData.roleName,
                                "type": "APP_ROLE",
                                "appAuths": authorities,
                                "desc": this.formData.roleDesc,
                                "formAuthType": this.formAuthType
                            }
                            if(this.formAuthType === 1){
                                let formAuths = {}
                                this.tableData.forEach(t => {
                                    formAuths[t.worksheetId] = []
                                    for (const key in t) {
                                        const element = t[key];
                                        if(element === true){
                                            formAuths[t.worksheetId].push(key)
                                        }
                                    }
                                })
                                data.formAuths = formAuths

                                if(this.formAdd && data.appAuths && !data.appAuths.includes('FORM_ADD')){
                                    data.appAuths.push('FORM_ADD')
                                }
                            }
                            editRole(data).then((res) => {
                                if(res.data && res.data.success){
                                    this.$message.success("修改成功！")
                                    for (let i = 0; i < this.appRoles.length; i++) {
                                        if(this.submitState.node.id === this.appRoles[i].id){
                                            this.appRoles[i].roleName = this.formData.roleName;
                                            this.appRoles[i].desc = this.formData.roleDesc;
                                            break;
                                        }
                                    }
                                } else {
                                    this.$message.error("修改失败！")
                                }
                            })
                        }
                    }
                    else {
                        return false;
                    }
                });
            },
            handleFormCheckChange(checked, name){
                // this.formAuthorities.find(auth => auth.name === name).checked = checked
                this.tableData.forEach(t => {
                    t[name] = checked
                    if(checked){
                        if(name ==='FORM_EDIT'){
                            // this.formAuthorities.find(auth => auth.name === 'FORM_READ').checked = checked
                            t['FORM_READ'] = checked
                        }
                        else if(name ==='FORM_DELETE'){
                            t['FORM_READ'] = checked
                            t['FORM_EDIT'] = checked
                        }
                        else if(name ==='ROW_EDIT_OWN' || name ==='ROW_DELETE_OWN'){
                            t['ROW_READ_OWN'] = checked
                            // this.formAuthorities.find(auth => auth.name === 'ROW_READ_OWN').checked = checked
                        }
                        else if(name ==='ROW_EDIT_ALL' || name ==='ROW_DELETE_ALL'){
                            t['ROW_READ_ALL'] = checked
                            // this.formAuthorities.find(auth => auth.name === 'ROW_READ_OWN').checked = checked
                        }
                    }else{
                        if(name ==='FORM_READ'){
                            t['FORM_EDIT'] = checked
                            t['FORM_DELETE'] = checked
                            // this.formAuthorities.find(auth => auth.name === 'FORM_EDIT').checked = checked
                            // this.formAuthorities.find(auth => auth.name === 'FORM_DELETE').checked = checked
                        }
                        else if(name ==='FORM_EDIT'){
                            t['FORM_DELETE'] = checked
                        }
                        else if(name ==='ROW_READ_OWN'){
                            if(t['ROW_READ_ALL'] === checked){
                                t['ROW_EDIT_ALL'] = checked
                                t['ROW_EDIT_OWN'] = checked
                                t['ROW_DELETE_ALL'] = checked
                                t['ROW_DELETE_OWN'] = checked
                            }
                            // this.formAuthorities.find(auth => auth.name === 'ROW_EDIT_ALL').checked = checked
                            // this.formAuthorities.find(auth => auth.name === 'ROW_EDIT_OWN').checked = checked
                            // this.formAuthorities.find(auth => auth.name === 'ROW_DELETE_ALL').checked = checked
                            // this.formAuthorities.find(auth => auth.name === 'ROW_DELETE_OWN').checked = checked
                        }
                        else if(name ==='ROW_READ_ALL'){
                            if(t['ROW_READ_OWN'] === checked){
                                t['ROW_EDIT_ALL'] = checked
                                t['ROW_EDIT_OWN'] = checked
                                t['ROW_DELETE_ALL'] = checked
                                t['ROW_DELETE_OWN'] = checked
                            }
                        }
                    }
                })
            },
            handleFormRowCheckChange(checked, name, row){
                row[name] = checked
                
                if(checked){
                    if(name ==='FORM_EDIT'){
                        row['FORM_READ'] = checked
                    }
                    else if(name ==='FORM_DELETE'){
                        row['FORM_READ'] = checked
                        row['FORM_EDIT'] = checked
                    }
                    else if(name ==='ROW_EDIT_OWN' || name ==='ROW_DELETE_OWN'){
                        row['ROW_READ_OWN'] = checked
                    }
                    else if(name ==='ROW_EDIT_ALL' || name ==='ROW_DELETE_ALL'){
                        row['ROW_READ_ALL'] = checked
                    }
                }else{
                    if(name ==='FORM_READ'){
                        row['FORM_EDIT'] = checked
                        row['FORM_DELETE'] = checked
                    }
                    else if(name ==='FORM_EDIT'){
                        row['FORM_DELETE'] = checked
                    }
                    else if(name ==='ROW_READ_OWN'){
                        if(row['ROW_READ_ALL'] === checked){
                            row['ROW_EDIT_ALL'] = checked
                            row['ROW_EDIT_OWN'] = checked
                            row['ROW_DELETE_ALL'] = checked
                            row['ROW_DELETE_OWN'] = checked
                        }
                    }
                    else if(name ==='ROW_READ_ALL'){
                        if(row['ROW_READ_OWN'] === checked){
                            row['ROW_EDIT_ALL'] = checked
                            row['ROW_EDIT_OWN'] = checked
                            row['ROW_DELETE_ALL'] = checked
                            row['ROW_DELETE_OWN'] = checked
                        }
                    }
                }
            },
            async handleAddRole() {
                this.dialogAddRoleVisible = true;
                this.submitState = {
                    state: "add",
                    node: {}
                }
                if(this.visualType === 'App'){
                    let worksheetList = await getAllWorksheet(this.appId)
                    let tableData = []

                    this.formAuthorities = this.formData.appAuthorities.form.filter(f => (f.group === 'DistributeSpecial' && f.name !== 'FORM_ADD'))
                    worksheetList.forEach(worksheet => {
                        let obj = {
                            worksheet: worksheet.name,
                            worksheetId: worksheet.id
                        }
                        this.formAuthorities.forEach(auth => {
                            obj[auth.name] = false
                            this.$set(auth, 'checked', false)
                        })
                        tableData.push(obj)
                    })
                    this.tableData = tableData
                }

                this.formData = {
                    title: '添加角色',
                    roleName: "",
                    roleDesc: "自定义权限",
                    appAuthorities: this.formData.appAuthorities,
                    indeterminate: {
                        editor: true,
                        portal: true,
                        form: true,
                        studio: true,
                        builder: true,
                    },
                    checkAll: {
                        editor: false,
                        portal: false,
                        form: false,
                        studio: false,
                        builder: false,
                    },
                    roleAuthorities: {
                        editor: [],
                        portal: [],
                        form: [],
                        studio: [],
                        builder: [],
                    }
                }
            },
            handleDeleteRole(role) {
                this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteRole({"id": role.id}).then((res) => {
                        if (res.data && res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });

                            let index = this.appRoles.findIndex(r => r.id === role.id);

                            if(index >= 0){
                                this.appRoles.splice(index, 1)
                            }
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleUpdateRole(role) {
                getRoleByID({
                    id: role.id,
                    visualType: this.visualType
                }).then(async (res) => {
                    if(res.data && res.data.success){

                        let data = res.data.data;
                        let roleAuthorities = {
                            editor: [],
                            portal: [],
                            form: [],
                            studio: [],
                            builder: [],
                        };
                        
                        for (const appAuthoritiesKey in this.formData.appAuthorities) {
                            let auth = this.formData.appAuthorities[appAuthoritiesKey];
                            for (let i = 0; i < auth.length; i++) {
                                if(!data.appAuths){
                                    break;
                                }
                                for (let j = 0; j < data.appAuths.length; j++) {
                                    if(data.appAuths[j] === auth[i].name){
                                        roleAuthorities[appAuthoritiesKey].push(data.appAuths[j]);
                                        break;
                                    }
                                }
                            }
                        }
                        this.submitState = {
                            state: "update",
                            node: role
                        }
                        if(this.visualType === 'App'){
                            this.formAdd = data?.appAuths?data.appAuths.includes('FORM_ADD'):false
                            this.formAuthType = data.formAuthType
                            let tableData = []
                            let worksheetList = await getAllWorksheet(this.appId)
                            this.formAuthorities = this.formData.appAuthorities.form.filter(f => (f.group === 'DistributeSpecial' && f.name !== 'FORM_ADD'))
                            if(this.formAuthType === 1){
                                let formAuths = data.formAuths
                                worksheetList.forEach(worksheet => {
                                    let obj = {
                                        worksheet: worksheet.name,
                                        worksheetId: worksheet.id
                                    }
                                    this.formAuthorities.forEach(auth => {
                                        let authArray = formAuths[worksheet.id]
                                        obj[auth.name] = authArray.includes(auth.name)
                                    })
                                    tableData.push(obj)
                                })
                            } else if(this.formAuthType === 0){
                                worksheetList.forEach(worksheet => {
                                    let obj = {
                                        worksheet: worksheet.name,
                                        worksheetId: worksheet.id
                                    }
                                    this.formAuthorities.forEach(auth => {
                                        obj[auth.name] = false
                                    })
                                    tableData.push(obj)
                                })
                            }
                            
                            this.tableData = tableData
                        }
                        
                        this.formData = {
                            title: '修改角色',
                            roleName: data.roleName,
                            roleDesc: data.desc,
                            appAuthorities: this.formData.appAuthorities,
                            indeterminate: {
                                editor: true,
                                portal: true,
                                form: true,
                                studio: true,
                                builder: true,
                            },
                            checkAll: {
                                editor: false,
                                portal: false,
                                form: false,
                                studio: false,
                                builder: false,
                            },
                            roleAuthorities: roleAuthorities
                        }
                        this.dialogAddRoleVisible = true;
                    }
                })
            },
            handleClickUser(user, role){
                if(user.isOwner && role.manage){
                    return;
                }
                user.check = !user.check;
                role.showDeleteUser.userSize = 0;
                let flag = true;
                for (let i = 0; i < role.users.length; i++) {
                    if(role.users[i].check){
                        role.showDeleteUser.visible = true;
                        role.showDeleteUser.userSize++;
                        flag = false;
                    }
                }

                if(flag){
                    role.showDeleteUser.visible = false;
                }
            },
            handleAddUser() {
                this.dialogAddUserVisible = false;
                let users = JSON.parse(JSON.stringify(this.currentRole.users));

                let roleLength = this.currentRole.userIds.length;
                for (let i = 0; i < this.userData.length; i++) {
                    if(this.userData[i].check){
                        users.push({
                            check: false,
                            nickName: this.userData[i].userAlia,
                            userId: this.userData[i].userId,
                        });
                    }
                }
                if(roleLength === users.length){
                    return;
                }

                let userIds = [];
                for (let i = 0; i < users.length; i++) {
                    userIds.push(users[i].userId)
                }
                updateUser({
                    "id": this.currentRole.id,
                    "userIds": userIds
                }).then((res) => {
                    if(res.data && res.data.success){
                        this.currentRole.users = users;
                        this.currentRole.userIds = userIds;
                        this.currentRole.userSize = userIds.length;
                        this.$message.success('添加成功！')
                    } else {
                        this.$message.error('添加失败！')
                    }
                })
            },
            handleAddAppUser(role){
                this.currentRole = role
                getUserList().then((res) => {
                    if(res.data && res.data.success){
                        let userData = [];
                        // console.log(res.data.data)
                        for (let i = 0; i < res.data.data.length; i++) {
                            let user = res.data.data[i];
                            let flag = true;
                            for (let j = 0; j < role.userIds.length; j++) {
                                if(role.userIds[j] === user.userId){
                                    flag = false;
                                    break;
                                }
                            }
                            if(flag){
                                userData.push({
                                    userId: user.userId,
                                    userAlia: user.name,
                                    check: false
                                })
                            }
                        }
                        // this.originUserData = JSON.parse(JSON.stringify(userTableData));
                        this.userData = userData
                        this.dialogAddUserVisible = true;
                    }
                })
            },
            handleDeleteUsers(role){
                this.$confirm('此操作将移除这些用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let userIds = [];
                    let users = []
                    for (let i = 0; i < role.users.length; i++) {
                        if(!role.users[i].check){
                            userIds.push(role.users[i].userId);
                            users.push(role.users[i]);
                        }
                    }
                    updateUser({
                        "id": role.id,
                        "userIds": userIds
                    }).then((res) => {
                        if(res.data && res.data.success){
                            role.userSize = users ? users.length : 0
                            role.userIds = userIds;
                            role.users = users;
                        }
                        role.showDeleteUser.visible = false
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                    role.showDeleteUser.visible = false
                });
            },
            handleCheckAllAppChange(val, type) {
                let authorities = [];
                for (let i = 0; i < this.formData.appAuthorities[type].length; i++) {
                    authorities.push(this.formData.appAuthorities[type][i].name);
                }
                this.formData.roleAuthorities[type] = val ? authorities : [];
                this.formData.indeterminate[type] = false;
            },
            handleCheckedAppAuthorityChange(value, type) {
                let checkedCount = value.length;

                this.formData.checkAll[type] = checkedCount === this.formData.appAuthorities[type].length;
                this.formData.indeterminate[type] = checkedCount > 0 && checkedCount < this.formData.appAuthorities[type].length;
            },
        }
    }
</script>

<style lang="less">
    .auth {
        .el-dialog{
            margin: 15px auto !important;
        }
    }
    .auth-header{
        width: 100%;
        height: 60px;
        flex: 0 0 80px;
        line-height: 60px;
        justify-content: space-between;
    }
    .auth-content{
        width: 100%;
        flex: 1 1 auto;
        align-items: center;
    }
    .auth-card {
        margin-bottom: 20px;
        border-radius: 3px;
    }
    .auth-card-header {
        justify-content: space-between;
        width: 800px;
        height: 80px;
        border-radius: 3px;
        padding: 10px 20px;
        cursor: pointer;
    }
    .auth-card-header:hover {
        background: #314153;
        border: 1px solid #4e5e76;
    }
    .auth-card-left{
        height: 100%;
        padding: 10px;
    }
    .auth-card-right{
        height: 100%;
        padding: 10px;
        align-items: center;
    }
    .auth-card-des{
        font-size: 12px;
        font-family: MicrosoftYaHei;
        color: #B4B4B4;
        margin-top: 5px;
    }
    .auth-card-count{
        width: 50px;
        text-align: center;
        height: 30px;
        line-height: 30px;
        font-size: 12px;
        border-radius: 3px;
        margin-left: 20px;
    }
    .auth-card-icon{
        margin-left: 20px;
        z-index: 100;
        width: 30px;
        text-align: center;
    }
    .auth-card-icon:hover {
        opacity: 1;
        background: rgba(245, 245, 245, 0.4);
        color: white !important;
    }
    .auth-card-extend {
        width: 800px;
    }
    .auth-extend-content{
        width: 100%;
        max-height: 300px;
        min-height: 80px;
        overflow-y: auto;
        flex-wrap: wrap;
    }
    .auth-user{
        width: 50%;
        height: 60px;
        padding: 10px;
        align-items: center;
        overflow: hidden;
        cursor: pointer;
    }
    .auth-user-img{
        text-align: center;
        color: rgb(142, 238, 255);
        background: rgba(10, 119, 236, 0.5);
        width: 40px;
        height: 40px;
        line-height: 40px;
        font-size: 12px;
        border-radius: 50%;
        overflow:hidden;/* 内容超出宽度时隐藏超出部分的内容 */
        text-overflow:ellipsis;/* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用。*/
        margin-left: 10px;
    }
    .auth-user-name{
        height: 40px;
        line-height: 40px;
        overflow:hidden;/* 内容超出宽度时隐藏超出部分的内容 */
        text-overflow:ellipsis;/* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用。*/
        margin-left: 10px;
    }
    .auth-user-owner{
        width: 50px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        overflow:hidden;/* 内容超出宽度时隐藏超出部分的内容 */
        text-overflow:ellipsis;/* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用。*/
        margin-left: 10px;
        font-size: 12px;
        color: #FFFFFF;
        border-radius: 8px;
        background: #028AFF;
    }
    .auth-extend-footer{
        width: 100%;
        height: 50px;
        justify-content: center;
        align-items: center;
    }
    .auth-extend-add{
        width: 100px;
        height: 35px;
        border-radius: 4px;
        border: 1px solid #4C84FF;
        color: #4C84FF;
        text-align: center;
        line-height: 35px;
        cursor: pointer;
    }
    .auth-extend-delete{
        width: 100px;
        height: 35px;
        border-radius: 4px;
        border: 1px solid #FF4747;
        margin-left: 20px;
        color: #FF4747;
        text-align: center;
        line-height: 35px;
        cursor: pointer;
    }
    .auth-add-user{
        width: 100%;
        height: 400px;
        margin-top: 10px;
        overflow-y: auto;
    }
    .auth-add-user-item{
        width: 100%;
        height: 30px;
        align-items: center;
        margin-top: 5px;
        cursor: pointer;
    }
    .auth-add-user-name {
        margin-left: 10px;
    }
    .detail{
        color: #009df1;
        font-size: 14px;
        margin-left: 10px;
        cursor: pointer
    }
</style>
